package org.blogwu.learn.algorithm.链表学习;

public class LinkedList<E> extends AbstractList<E> {
    private Node<E> first;

    private static class Node<E> {
        E element;
        Node<E> next;

        public Node(E element, Node<E> next) {
            this.element = element;
            this.next = next;
        }
    }

    @Override
    public void clear() {
        size = 0;
        first = null;
    }

    @Override
    public E get(int index) {
        return node(index).element;
    }

    @Override
    public E set(int index, E element) {
        rangeCheck(index);
        Node<E> previous = this.node(index);
        E old = previous.element;
        previous.next.element = element;
        return old;
    }

    @Override
    public void add(int index, E element) {
        if (index == 0) {
            Node<E> newFirst = new Node<E>(element, first);
            first = newFirst;
        } else {
            Node<E> previous = node(index - 1);
            previous.next = new Node<E>(element, previous.next);
            ;
        }
        size++;
    }

    @Override
    public E remove(int index) {
        E old = null;
        if (index == 0 && size > 0) {
            first = first.next;
        } else {
            Node<E> previous = node(index - 1);
            old = previous.next.element;
            previous.next = previous.next.next;
        }
        size--;
        return old;
    }

    @Override
    public int indexOf(E element) {
        if (element == null) {
            return -1;
        }
        Node<E> current = first;
        for (int i = 0; i < size; i++) {
            if (current.element.equals(element)) {
                return i;
            }
        }
        return -1;
    }

    /**
     * 获取index位置对应的节点对象
     *
     * @param index
     * @return
     */
    private Node<E> node(int index) {
        rangeCheck(index);
        Node<E> current = first;
        for (int i = 0; i <= index; i++) {
            if (i == index) {
                return current;
            } else {
                current = current.next;
            }
        }
        return null;
    }

    @Override
    public String toString() {
        StringBuilder string = new StringBuilder();
        string.append("size=").append(size).append(", [");
        Node<E> node = first;
        for (int i = 0; i < size; i++) {
            if (i != 0) {
                string.append(", ");
            }

            string.append(node.element);

            node = node.next;
        }
        string.append("]");

//		Node<E> node1 = first;
//		while (node1 != null) {
//			
//			
//			node1 = node1.next;
//		}
        return string.toString();
    }
}
